<?php
namespace control;
/*
*销售汇总表类
*/

class saleStatisticsClass extends adIndexClass
{
    private const page = 'saleStatistics';
    private const title = '销售汇总表';
    private const workflow    = ['按商品', '按客户', '按销售员'];
    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'clientSearch':
                $tr = [
                    'orderNo'          => [
                        'name'  => '客户编码',
                        'width' => 150,
                    ],
                    'companyName'          => [
                        'name'  => '客户名称',
                        'width' => 150,
                    ],
                    'code'          => [
                        'name'  => '产品编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName' => [
                        'name'  => "产品名称",
                        'width' => 200,
                    ],
                    'model'  => [
                        'name'  => "规格型号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'unit'         => [
                        'name'  => '单位',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '销售数量',
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'price'          => [
                        'name'  => '单价('.static::$unit.')',
                        'width' => 130,
                    ],
                    'notaxMoney'          => [
                        'name'  => '金额('.static::$unit.')',
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'taxMoney'          => [
                        'name'  => '税额('.static::$unit.')',
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'money'          => [
                        'name'  => '价税合计('.static::$unit.')',
                        'width' => 130,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'saleManSearch':
                $tr = [
                    'manager'          => [
                        'name'  => '销售员',
                        'width' => 100,
                    ],
                    'code'          => [
                        'name'  => '产品编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName' => [
                        'name'  => "产品名称",
                        'width' => 300,
                    ],
                    'model'  => [
                        'name'  => "规格型号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'unit'         => [
                        'name'  => '单位',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '销售数量',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'price'          => [
                        'name'  => '单价('.static::$unit.')',
                        'width' => 120,
                    ],
                    'notaxMoney'          => [
                        'name'  => '金额('.static::$unit.')',
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'taxMoney'          => [
                        'name'  => '税额('.static::$unit.')',
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'money'          => [
                        'name'  => '价税合计('.static::$unit.')',
                        'width' => 130,
                        'sort' => 1,
                    ]
                ];
                break;
            case 'saleSendSearch':
                $tr = [
                    'orderNo'          => [
                        'name'  => '客户编码',
                        'width' => 150,
                    ],
                    'companyName'          => [
                        'name'  => '客户名称',
                        'width' => 200,
                    ],
                    'code'          => [
                        'name'  => '产品编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName' => [
                        'name'  => "产品名称",
                        'width' => 200,
                    ],
                    'model'  => [
                        'name'  => "规格型号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'unit'         => [
                        'name'  => '主单位',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '发货数量',
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'notaxMoney'          => [
                        'name'  => '发货金额('.static::$unit.')',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'taxMoney'          => [
                        'name'  => '发货税额('.static::$unit.')',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'money'          => [
                        'name'  => '发货价税合计('.static::$unit.')',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'code'          => [
                        'name'  => '产品编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName' => [
                        'name'  => "产品名称",
                        'width' => 300,
                    ],
                    'model'  => [
                        'name'  => "规格型号",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'unit'         => [
                        'name'  => '单位',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '销售数量',
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'price'          => [
                        'name'  => '单价('.static::$unit.')',
                        'width' => 130,
                    ],
                    'notaxMoney'          => [
                        'name'  => '金额('.static::$unit.')',
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'taxMoney'          => [
                        'name'  => '税额('.static::$unit.')',
                        'width' => 130,
                        'sort' => 1,
                    ],
                    'money'          => [
                        'name'  => '价税合计('.static::$unit.')',
                        'width' => 130,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions(string $workFlow ='按商品',$isAsync = true)
    {
        $html = '';
        if ($workFlow == '按商品') {
            //生成查询表单
            $html = $this->tableShow([
                [
                    [
                        "产品编码" => text(array("name" => "code")),
                        "产品名称"   => text(array("name" => "materialName")),
                        "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    ]
                ]
            ],1);
        }elseif($workFlow == '按客户'){
            $html = $this->tableShow([
                [
                    [
                        "客户编码" => text(array("name" => "clientCode")),
                        //"客户名称"   => clientProfileClass::kehuSelect(array('title' => '')),
                        "客户名称"   => selectMultiple(array('table' => 'kehu', 'sqlField' => 'companyName', 'sqlId' => 'khid', 'name' => 'khid', 'where' => " coid = '" . self::$coid . "' ")),
                        "产品编码" => text(array("name" => "code")),
                    ],
                    [
                        "产品名称"   => text(array("name" => "materialName")),
                        "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    ]
                ]
            ],1);
        }elseif($workFlow == '按销售员'){
            $html = $this->tableShow([
                [
                    [
                        "销售员" => selectMultiple(array('table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager')),
                        "产品编码" => text(array("name" => "code")),
                        "产品名称"   => text(array("name" => "materialName")),
                    ],
                    [
                        "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    ]
                ]
            ],1);
        }

        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow ='按商品'): string
    {
        //生成查询表单
        $html = $this->homeOptions($workFlow,false);
        $button = "";
        if ($workFlow == '按商品') {
            if ($this->power(self::page, "export")) {
                $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',source:'material',classify:'销售商品汇总'})\">导出</span>";
            }
        }elseif ($workFlow =='按客户'){
            if ($this->power('clientStatistics', "export")) {
                $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',source:'client',classify:'销售客户汇总'})\">导出</span>";
            }
        }elseif ($workFlow =='按销售员'){
            if ($this->power('saleManStatistics', "export")) {
                $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',source:'saleman',classify:'销售员汇总'})\">导出</span>";
            }
        }
        return $this->search($html, layout: 'pop', toolButton: $button);
    }

    /*列表-查询条件*/
    public function home($workFlow = '按商品')
    {
        $data = [
            "id" => "all",
            "menu" => [
                "home" => "按商品",
                "client" => "按客户",
                "saleMan" => "按销售员",
            ]
        ];
        $data['html'] = $this->homeForm($workFlow);
        return $this->tab($data);


//        $html = $this->homeOptions(false);
//        //控件
//        $button = "";
//        if ($this->power(self::page, "export")) {
//            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',source:'material',classify:'销售商品汇总'})\">导出</span>";
//        }
//        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.coid"=>self::$coid,
            "b.state"=>'已确认'
        );
        $and = "";
        if ($this->post('createTime')) {
            //单据日期
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and b.recordDate >='{$timeArr[0]}' and b.recordDate <='{$timeArr[1]}'";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and." group by a.materialId,a.unit";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'code',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => "sale_order_detail as a join sale_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"
            any_value(c.code) as code,
            any_value(c.name) as materialName,
            any_value(c.model) as model,
            a.unit,
            any_value(a.materialId) as materialId,
            ifnull(sum(any_value(a.num)),0) as num,
            ifnull(sum(any_value(a.money)),0) as money,
            ifnull(sum(any_value(a.taxMoney)),0) as taxMoney,
            ifnull(sum(any_value(a.money)-any_value(a.taxMoney)),0) as notaxMoney
            ",
            "where" => $where,
            "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "num":
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    case "price":
                        $price =$array['num']>0? self::formattingFigure($array['money']/$array['num'],'pricePrecision'):0;
                        $row[] = $price;
                        break;
                    case "notaxMoney":
                    case "taxMoney":
                    case "money":
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "sale_order_detail as a join sale_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => search(array("like" => $like, "=" => $equal)) . $and,
            'field'  => "ifnull(sum(a.num),0) as num,
            ifnull(sum(a.money),0) as money,
            ifnull(sum(a.taxMoney),0) as taxMoney,
            ifnull(sum(a.money-a.taxMoney),0) as notaxMoney",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'notaxMoney'   => self::lostZero($totalQuery['notaxMoney']),
            'taxMoney' => self::lostZero($totalQuery['taxMoney']),
            'money'    => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function clientOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "客户编码" => text(array("name" => "clientCode")),
                    //"客户名称"   => clientProfileClass::kehuSelect(array('title' => '')),
                    "客户名称"   => selectMultiple(array('table' => 'kehu', 'sqlField' => 'companyName', 'sqlId' => 'khid', 'name' => 'khid', 'where' => " coid = '" . self::$coid . "' ")),
                    "产品编码" => text(array("name" => "code")),
                ],
                [
                    "产品名称"   => text(array("name" => "materialName")),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 按客户
     * @return bool|string
     */
    public function client(){
        $json['html'] = $this->homeForm('按客户');
        return json_encode($json, 320);
//        $html = $this->clientOptions(false);
//        //控件
//        $button = "";
//        if ($this->power('clientStatistics', "export")) {
//            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',source:'client',classify:'销售客户汇总'})\">导出</span>";
//        }
//        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 按客户
     * @return bool|string
     */
    public function clientSearch()
    {
        //like查询数组
        $like = array(
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.coid"=>self::$coid,
            "b.state"=>'已确认',
            "b.khid"=>$this->post('khid')
        );
        $and = "";
        if ($this->post('clientCode')) {
            $and.=" and b.khid in (select khid from kehu where orderNo like '%".$this->post('clientCode')."%' and coid = '".self::$coid."')";
        }
        if ($this->post('createTime')) {
            //单据日期
            $and.=self::timeComparison($this->post('createTime'),field: 'b.recordDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and." group by b.khid,a.materialId,a.unit";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'code',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => "sale_order_detail as a join sale_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"
            b.khid,
            any_value(c.code) as code,
            any_value(c.name) as materialName,
            any_value(c.model) as model,
            a.unit,
            any_value(a.materialId) as materialId,
            ifnull(sum(any_value(a.num)),0) as num,
            ifnull(sum(any_value(a.money)),0) as money,
            ifnull(sum(any_value(a.taxMoney)),0) as taxMoney,
            ifnull(sum(any_value(a.money)-any_value(a.taxMoney)),0) as notaxMoney
            ",
            "where" => $where,
            "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['client'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "orderNo":
                    case "companyName":
                        $kehu = query('kehu',"khid = '$array[khid]'");
                        $row[] = $kehu[$key];
                        break;
                    case "num":
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    case "price":
                        $price =$array['num']>0? self::formattingFigure($array['money']/$array['num'],'pricePrecision'):0;
                        $row[] = $price;
                        break;
                    case "notaxMoney":
                    case "taxMoney":
                    case "money":
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "sale_order_detail as a join sale_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => search(array("like" => $like, "=" => $equal)) . $and,
            'field'  => "ifnull(sum(a.num),0) as num,
            ifnull(sum(a.money),0) as money,
            ifnull(sum(a.taxMoney),0) as taxMoney,
            ifnull(sum(a.money-a.taxMoney),0) as notaxMoney",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'notaxMoney'   => self::lostZero($totalQuery['notaxMoney']),
            'taxMoney' => self::lostZero($totalQuery['taxMoney']),
            'money'    => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function saleManOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "销售员" => selectMultiple(array('table' => 'staff', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'manager')),
                    "产品编码" => text(array("name" => "code")),
                    "产品名称"   => text(array("name" => "materialName")),
                ],
                [
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 按销售员
     * @return bool|string
     */
    public function saleMan(){
        $json['html'] = $this->homeForm('按销售员');
        return json_encode($json, 320);
//        $html = $this->saleManOptions(false);
//        //控件
//        $button = "";
//        if ($this->power('saleManStatistics', "export")) {
//            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',source:'saleman',classify:'销售员汇总'})\">导出</span>";
//        }
//        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 按销售员
     * @return bool|string
     */
    public function saleManSearch()
    {
        //like查询数组
        $like = array(
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.coid"=>self::$coid,
            "b.state"=>'已确认',
            "b.manager"=>$this->post('manager')
        );
        $and = "";
        if ($this->post('createTime')) {
            //单据日期
            $and.=self::timeComparison($this->post('createTime'),field: 'b.recordDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and." group by b.manager,a.materialId,a.unit";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'code',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => "sale_order_detail as a join sale_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"
            b.manager,
            any_value(c.code) as code,
            any_value(c.name) as materialName,
            any_value(c.model) as model,
            a.unit,
            any_value(a.materialId) as materialId,
            ifnull(sum(any_value(a.num)),0) as num,
            ifnull(sum(any_value(a.money)),0) as money,
            ifnull(sum(any_value(a.taxMoney)),0) as taxMoney,
            ifnull(sum(any_value(a.money)-any_value(a.taxMoney)),0) as notaxMoney
            ",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['saleman'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "num":
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    case "price":
                        $price =$array['num']>0? self::formattingFigure($array['money']/$array['num'],'pricePrecision'):0;
                        $row[] = $price;
                        break;
                    case "notaxMoney":
                    case "taxMoney":
                    case "money":
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "sale_order_detail as a join sale_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => search(array("like" => $like, "=" => $equal)) . $and,
            'field'  => "ifnull(sum(a.num),0) as num,
            ifnull(sum(a.money),0) as money,
            ifnull(sum(a.taxMoney),0) as taxMoney,
            ifnull(sum(a.money-a.taxMoney),0) as notaxMoney",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'notaxMoney'   => self::lostZero($totalQuery['notaxMoney']),
            'taxMoney' => self::lostZero($totalQuery['taxMoney']),
            'money'    => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function saleSendOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "客户编码" => text(array("name" => "clientCode")),
                    "客户名称"   => clientProfileClass::kehuSelect(array('title' => '')),
                    "产品编码" => text(array("name" => "code")),
                ],
                [
                    "产品名称"   => text(array("name" => "materialName")),
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 按客户
     * @return bool|string
     */
    public function saleSend(){
        $html = $this->clientOptions(false);
        //控件
        $button = "";
        if ($this->power('saleSendStatistics', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',source:'saleSend',classify:'销售发货汇总'})\">导出</span>";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 按客户
     * @return bool|string
     */
    public function saleSendSearch()
    {
        //like查询数组
        $like = array(
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.coid"=>self::$coid,
            "b.state"=>'已确认',
            "b.khid"=>$this->post('khid')
        );
        $and = "";
        if ($this->post('clientCode')) {
            $and.=" and b.khid in (select khid from kehu where orderNo like '%".$this->post('clientCode')."%' and coid = '".self::$coid."')";
        }
        if ($this->post('createTime')) {
            //单据日期
            $and.=self::timeComparison($this->post('createTime'),field: 'b.recordDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and." group by b.khid,a.materialId";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'code',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => "sale_send_order_detail as a join sale_send_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"
            b.khid,
            any_value(c.code) as code,
            any_value(c.name) as materialName,
            any_value(c.model) as model,
            any_value(c.unit) as unit,
            any_value(a.materialId) as materialId,
            ifnull(SUM((CASE WHEN a.unit = c.unit_one THEN a.num*c.unit_one_num WHEN a.unit = c.unit_two THEN a.num*c.unit_two_num ELSE a.num END)),0) AS num,
            ifnull(sum(any_value(a.money)),0) as money,
            ifnull(sum(any_value(a.taxMoney)),0) as taxMoney,
            ifnull(sum(any_value(a.money)-any_value(a.taxMoney)),0) as notaxMoney
            ",
            "where" => $where,
            "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['saleSend'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "orderNo":
                    case "companyName":
                        $kehu = query('kehu',"khid = '$array[khid]'");
                        $row[] = $kehu[$key];
                        break;
                    case "num":
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    case "notaxMoney":
                    case "taxMoney":
                    case "money":
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "sale_send_order_detail as a join sale_send_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => search(array("like" => $like, "=" => $equal)) . $and,
            'field'  => "ifnull(SUM((CASE WHEN a.unit = c.unit_one THEN a.num*c.unit_one_num WHEN a.unit = c.unit_two THEN a.num*c.unit_two_num ELSE a.num END)),0) AS num,
            ifnull(sum(a.money),0) as money,
            ifnull(sum(a.taxMoney),0) as taxMoney,
            ifnull(sum(a.money-a.taxMoney),0) as notaxMoney",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'notaxMoney'   => self::lostZero($totalQuery['notaxMoney']),
            'taxMoney' => self::lostZero($totalQuery['taxMoney']),
            'money'    => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $source = $this->get('source');
        switch ($source) {
            case "saleman":
                $power = 'saleManStatistics';
                break;
            case "client":
                $power = 'clientStatistics';
                break;
            default:
                $power = self::page;
        }
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power($power, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } elseif(empty($source)){
            $_SESSION['warn'] = '未找到类型';
        }else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            if($source =='saleman'){
                $sql = $_SESSION[self::page]['saleman'];
                $result = sqlFind($sql);
                //导出数据生成
                foreach ($result as $array){
                    $column = [];
                    $price =$array['num']>0? self::formattingFigure($array['money']/$array['num'],'pricePrecision'):0;
                    foreach ($tempFieldAll as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '销售员'=>self::findStaff($array['manager']),
                                '产品编码'=>$array['code'],
                                '产品名称'=>$array['materialName'],
                                '规格型号'=>$array['model'],
                                '单位'=>$array['unit'],
                                '销售数量'=>self::lostZero($array['num'],'numPrecision'),
                                '单价'=>self::lostZero($price,'pricePrecision'),
                                '未税金额'=>self::lostZero($array['notaxMoney'],'amount'),
                                '税额'=>self::lostZero($array['taxMoney'],'amount'),
                                '价税合计'=>self::lostZero($array['money'],'amount'),
                                default=>'',
                            };
                        }
                    }
                    $data[] = $column;
                }
            }elseif($source =='client'){
                $sql = $_SESSION[self::page]['client'];
                $result = sqlFind($sql);
                //导出数据生成
                foreach ($result as $array){
                    $column = [];
                    $price =$array['num']>0? self::formattingFigure($array['money']/$array['num'],'pricePrecision'):0;
                    $kehu = query('kehu',"khid = '$array[khid]'");
                    foreach ($tempFieldAll as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '客户编码'=>$kehu['orderNo'],
                                '客户名称'=>$kehu['companyName'],
                                '产品编码'=>$array['code'],
                                '产品名称'=>$array['materialName'],
                                '规格型号'=>$array['model'],
                                '单位'=>$array['unit'],
                                '销售数量'=>self::lostZero($array['num'],'numPrecision'),
                                '单价'=>self::lostZero($price,'pricePrecision'),
                                '未税金额'=>self::lostZero($array['notaxMoney'],'amount'),
                                '税额'=>self::lostZero($array['taxMoney'],'amount'),
                                '价税合计'=>self::lostZero($array['money'],'amount'),
                                default=>'',
                            };
                        }
                    }
                    $data[] = $column;
                }
            }elseif($source =='saleSend'){
                $sql = $_SESSION[self::page]['saleSend'];
                $result = sqlFind($sql);
                //导出数据生成
                foreach ($result as $array){
                    $column = [];
                    $kehu = query('kehu',"khid = '$array[khid]'");
                    foreach ($tempFieldAll as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '客户编码'=>$kehu['orderNo'],
                                '客户名称'=>$kehu['companyName'],
                                '产品编码'=>$array['code'],
                                '产品名称'=>$array['materialName'],
                                '规格型号'=>$array['model'],
                                '主单位'=>$array['unit'],
                                '发货数量'=>self::lostZero($array['num'],'numPrecision'),
                                '发货金额'=>self::lostZero($array['notaxMoney'],'amount'),
                                '发货税额'=>self::lostZero($array['taxMoney'],'amount'),
                                '发货价税合计'=>self::lostZero($array['money'],'amount'),
                                default=>'',
                            };
                        }
                    }
                    $data[] = $column;
                }
            }else{
                $sql = $_SESSION[self::page]['sql'];
                $result = sqlFind($sql);
                //导出数据生成
                foreach ($result as $array){
                    $column = [];
                    $price =$array['num']>0? self::formattingFigure($array['money']/$array['num'],'pricePrecision'):0;
                    foreach ($tempFieldAll as $templateField){
                        if ($templateField['display']){
                            $column[] = match ($templateField['columnName']){
                                '产品编码'=>$array['code'],
                                '产品名称'=>$array['materialName'],
                                '规格型号'=>$array['model'],
                                '单位'=>$array['unit'],
                                '销售数量'=>self::lostZero($array['num'],'numPrecision'),
                                '单价'=>self::lostZero($price,'pricePrecision'),
                                '未税金额'=>self::lostZero($array['notaxMoney'],'amount'),
                                '税额'=>self::lostZero($array['taxMoney'],'amount'),
                                '价税合计'=>self::lostZero($array['money'],'amount'),
                                default=>'',
                            };
                        }
                    }
                    $data[] = $column;
                }
            }
            $text = $this->control['name'] . "导出了销售汇总表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "销售汇总表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }


    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            '销售员汇总'=>[
                [
                    'columnName'=>'销售员',
                    'aliasName'=>'销售员',
                ],
                [
                    'columnName'=>'产品编码',
                    'aliasName'=>'产品编码',
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'销售数量',
                    'aliasName'=>'销售数量',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价('.static::$unit.')',
                ],
                [
                    'columnName'=>'未税金额',
                    'aliasName'=>'未税金额('.static::$unit.')',
                ],
                [
                    'columnName'=>'税额',
                    'aliasName'=>'税额('.static::$unit.')',
                ],
                [
                    'columnName'=>'价税合计',
                    'aliasName'=>'价税合计('.static::$unit.')',
                ],
            ],
            '销售客户汇总'=>[
                [
                    'columnName'=>'客户编码',
                    'aliasName'=>'客户编码',
                ],
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',
                ],
                [
                    'columnName'=>'产品编码',
                    'aliasName'=>'产品编码',
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'销售数量',
                    'aliasName'=>'销售数量',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价('.static::$unit.')',
                ],
                [
                    'columnName'=>'未税金额',
                    'aliasName'=>'未税金额('.static::$unit.')',
                ],
                [
                    'columnName'=>'税额',
                    'aliasName'=>'税额('.static::$unit.')',
                ],
                [
                    'columnName'=>'价税合计',
                    'aliasName'=>'价税合计('.static::$unit.')',
                ],
            ],
            '销售发货汇总'=>[
                [
                    'columnName'=>'客户编码',
                    'aliasName'=>'客户编码',
                ],
                [
                    'columnName'=>'客户名称',
                    'aliasName'=>'客户名称',
                ],
                [
                    'columnName'=>'产品编码',
                    'aliasName'=>'产品编码',
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'主单位',
                    'aliasName'=>'主单位',
                ],
                [
                    'columnName'=>'发货数量',
                    'aliasName'=>'发货数量',
                ],
                [
                    'columnName'=>'发货金额',
                    'aliasName'=>'发货金额('.static::$unit.')',
                ],
                [
                    'columnName'=>'发货税额',
                    'aliasName'=>'发货税额('.static::$unit.')',
                ],
                [
                    'columnName'=>'发货价税合计',
                    'aliasName'=>'发货价税合计('.static::$unit.')',
                ],
            ],
            default=>  [
                [
                    'columnName'=>'产品编码',
                    'aliasName'=>'产品编码',
                ],
                [
                    'columnName'=>'产品名称',
                    'aliasName'=>'产品名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'销售数量',
                    'aliasName'=>'销售数量',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价('.static::$unit.')',
                ],
                [
                    'columnName'=>'未税金额',
                    'aliasName'=>'未税金额('.static::$unit.')',
                ],
                [
                    'columnName'=>'税额',
                    'aliasName'=>'税额('.static::$unit.')',
                ],
                [
                    'columnName'=>'价税合计',
                    'aliasName'=>'价税合计('.static::$unit.')',
                ],
            ]
        };
    }
}

